<?php 
class builtListHelper extends AppHelper {

    var $controller = null;
    var $helpers = array('Html','Form','Time','Number','Paginator','Session','TextDate');
    private $userFunction;
    private $_html =array('color'=>null,'width'=>null,'height'=>null,'style'=>null,'align'=>null,'border'=>null,'class'=>null);
    private $_dato;
    private $_key;
    public $i; // para jalar el numero del registro desde el callback
    public $paginator_url = '';
	public $onlyStyle = array();
	public $defaultAttr = array('div'=>false,'label'=>false,'value'=>'','size'=>10);
	public $defaultAttrhRef = array('href'=>'#');
	public $defaultTable = array('width'=>'500px','border'=>1,'cellspacing'=>1,'class'=>'tablatipo');
	public $botom = array('botom'=>array(// Pondra todos los botones con <a>texto</a>
							//'default'=>false, // CREARA LAS BOTONES EDIT,ERASE, ADD POR DEFECTO
							'edit'=>array(
										'img'=>true,
										'texto'=>'icons/page_edit.png',										
										'atr'=>array('href'=>'#','title'=>'Editar Registro','class'=>'editFila','border'=>0),
										'celda'=>array('align'=>'right')
										),
							'add'=>array(
										'img'=>true,
										'texto'=>'icons/save.png',
										'atr'=>array('href'=>'#','title'=>'Agregar Registro','class'=>'agregarFila','border'=>0),
										'celda'=>array('align'=>'right')
										),
							'erase'=>array(
										'img'=>true,
										'texto'=>'icons/cross.png',
										'atr'=>array('href'=>'#','title'=>'Eliminar Registros','class'=>'borrarFila','border'=>0),
										'celda'=>array('align'=>'right'),										
										)                  
							));
							
	public $styles = array(
						1=>array(
								'type'=>'class',
								'name'=>'tablatipo',
								'belong'=>'table',
								'atr'=>array('max-width'=>'600px')
							),
						2=>array(
								'type'=>'class',
								'name'=>'ampliarCuerpo',
								'belong'=>'div',
								'atr'=>array(
									'max-height'=>'600px',
									'overflow'=>'auto')
								),
						3=>array(		
								'type'=>'class',
								'name'=>'tr.celdaTabla td',								
								'atr'=>array(
									'background'=>'#F5F6CE')							
								),
						4=>array(
								'type'=>'class',
								'name'=>'mostrarTotalCelda',
								'atr'=>array(
									'text-align'=>'left',
									'padding-left'=>'3px',
									'font-weight'=>'bold'
									)
							)
					);

    function startup(&$controller){
        $this->controller = $controller;
    }


    var $tags = array(
        'table' => '<table>%s</table>',
		'tr' => '<tr %s>%s</tr>',
		'td' => '<td %s>%s</td>',
		'th' => '<th %s>%s</th>',
		'strong' => '<strong>%s</strong>',
		'a'=>'<a href="%s">%s</a>',
		'aref'=>'<a %s>%s</a>',
		'aclass'=>'<a href="%s" class="%s">%s</a>');
    
    private function getProperty($pro=array(), $css = false){
		$property=' ';
		foreach($pro as $name => $value){
			if(!is_array($name)){
				if($css){
					$property .= $name.':'.$value.'; ';
				}else{
					$property .= $name.'="'.$value.'" ';
				}
			}
		}
		return $property;
    }
	
    private function getId($key,$id=false){
		$valor='';
		if($id==true){
			$strin	= str_replace(array('[', ']'), array('',''), str_replace(array('][','_'),array('.','.'),$key));
			$explod = explode('.',$strin);
			foreach($explod as $v=>$a){
				$valor .= ucwords($a);
			}
		}else{
			$valor = str_replace(array('[', ']'), array('',''), str_replace('][','.',$key));
		}
		return $valor;
    }
	
	private function getValue($dato, $key, $strong = false){
        $key = $key.'';
		$val = str_replace('[','',$key);
        $val = $val.'';
		$dat = explode(']',$val);
		$valor = $dato;
		foreach($dat as $d){
			if($d != false){
            	$valor = isset($valor[$d])?$valor[$d]:false;
        	}
		}
		return trim($valor);
    }
	
    private function soloInput($name, $atr = array()){
		$form = $this->Form;
		$html = $this->Html;	
		return  $form->input( $name , array_merge($this->defaultAttr,$atr));	
	}
	# solo para ingresar los css
	private function Css($camposCss=null){
		if(empty($camposCss)){
			$camposCss = $this->styles;	
		}
		$n 			= chr(13); 			
		$todoName 	= array();	
		$body 		= ''; 
		$class 		= '';		
		$soloCss 	= array();
		foreach($camposCss as $css){
			if($css['type']=='class'){
				$class = '.';
			}else{
				$class = '#';
			}
			if(strstr($css['name'], $class)){
				$body.= $css['name'].'{'.$n;										
			}else{
				$body.= $class.$css['name'].'{'.$n;
			}
			$body.= $this->getProperty($css['atr'],true);
			$body.= $n.'}'.$n;
			
			$soloCss['class'] = $css['name'];			
			
			unset($css['atr']);
			if(!empty($css['belong'])){
				$this->onlyStyle['type'][ $css['belong'] ] = $soloCss;
			}
			$todoName[] = $css['name'];
		}	
		// solo los div con default
		foreach($this->styles as $val){
			if(in_array($val['name'], $todoName)){
				continue;	
			}
			
			if($val['type']=='class'){
				$class = '.';
			}else{
				$class = '#';
			}
			if(strstr($val['name'], $class)){
				$body.= $val['name'].'{'.$n;										
			}else{
				$body.= $class.$val['name'].'{'.$n;
			}
			$body.= $this->getProperty($val['atr'],true);
			$body.= $n.'}'.$n;
			
			$soloval['class'] = $val['name'];			
			
			unset($val['atr']);
			if(!empty($val['belong'])){
				$this->onlyStyle['type'][ $val['belong'] ] = $soloCss;
			}
		}
		$estilo = '';	
		$estilo.= '<style type="text/css">'.$n; 		
		$estilo.= $body; 		
		$estilo.= $n.'</style>';		
		return $estilo;
	}
	# para añadir el Jquery
	private function jquery($insert=array(), $botom=array(), $model=array(), $head, $body, $count = null){
		$n = chr(13); 		
		$form = $this->Form;
		$html = $this->Html;
		$tr = $this->getId($insert['input']['name'],true);
		$add = $botom['add']['atr']['class'];
		$edit = $botom['edit']['atr']['class'];
		$editCelda = !empty($botom['edit']['celda'])?$this->getProperty($botom['edit']['celda']):'';		
		$delete = $botom['erase']['atr']['class'];		
		$modelHead = 'Fila';
		$modelBody = 'Detalle';		
		$afterFila 	= 'row0';
		$afterFilaKey 	= 'row';
		if(!empty($insert['after'])){                        
			$afterFila 	= empty($insert['after']['atr']['id'])?$afterFila:$insert['after']['atr']['id'];
			$afterFilaKey 	= empty($insert['after']['atr']['key'])?$afterFilaKey:$insert['after']['atr']['key'];                        
		}                
                
		if(!empty($model)){
			$modelHead = $model['head']['name'];
			$modelBody = $model['body']['name'];
		}
		// SOLO PARA CAMPOS DE BORRADO Y CONTADOR
		$defaultTotal	= $this->getId('Total.item',true);
		$defaultBorrar 	= $this->getId('Borrar.item',true);		
		if(!empty($count)){
			$defaultTotal	= $this->getId($count['total'],true);
			$defaultBorrar 	= $this->getId($count['borrar'],true);
		}
		
		$thtml 			= ''; # construimos la tabla para jquery
		$camposHidden	= '';
		$editarFila		= '';	
		$onlyToChecked	= '';	
		$validacionChecked = '';
		$z = 0;               
		foreach($body as $key=>$campo){
			$z++;
			$soloInput 		= '';
			$key = $modelBody.'.$i.'.$this->getId($key);
			# solo para boton editar			
			$editarKey = str_replace('$i','"+$i+"',$this->getId($key,true));
			if(empty($campo['checkbox'])){
				$editarFila.= '$("#'.$this->getId($campo['campo'],true).'").val($("#'.$editarKey.'").val());'.$n;
			}else{
				$editarFila.= '$("#'.$this->getId($campo['campo'],true).'").attr("checked",$("#'.$editarKey.'").attr("checked"));'.$n;	
			}
			# construimos las celdas para la tabla Jquery
			if(!empty($campo['checkbox'])){	
				$valorFila = ' $filaNumero'.$z.' = $(\'#'.$this->getId($campo['campo'],true).'\').attr(\'checked\') ;'.$n;
				$keyChecked = $this->getId($key,true);
				$keyChecked = str_replace('$i','\'+$i+\'',$keyChecked);
				$validacionChecked.= '
							if($filaNumero'.$z.'){
								$(\'#'.$keyChecked.'\').attr(\'checked\',true);	
								$(\'#'.$this->getId($campo['campo'],true).'\').attr(\'checked\',false);
							}
					';
				unset($this->defaultAttr['div']);
				unset($this->defaultAttr['label']);
				unset($this->defaultAttr['value']);
				$onlyToChecked.= $valorFila;							
				//$atributo = array_merge($this->defaultAttr, array('checked'=>'\'+$filaNumero'.$z.'+\'','id'=>$this->getId($key,true)));					
				$atributo = array_merge($this->defaultAttr, array('id'=>$this->getId($key,true)));					
			}else{
				$valorFila = '$(\'#'.$this->getId($campo['campo'],true).'\').val()';
				$atributo = array_merge($this->defaultAttr, array('value'=>'\'+'.$valorFila.'+\''));				
			}						
			if(!empty($campo['atr'])){
				$atributo = array_merge($atributo,!empty($campo['atr'])?$campo['atr']:array());				
			}
			// solo en caso de que tengas las celdas para alinear
			$atrCelda = '';
			if(!empty($campo['celda'])){
				$atrCelda = $this->getProperty($campo['celda']);
			}
			if(!empty($campo['checkbox'])){	
				unset($atributo['style']);
				unset($atributo['size']);
				//$input = $form->checkbox($key, $atributo);			
				$input = '<input '.$this->getProperty($atributo) .' name="data['.$modelBody.'][$i]['.$this->getId($key,true).']"/>' ;	
				//printDie();
			}else{
				$input = $form->text($key, $atributo);
			}
			$input = str_replace('&#039;',"'",$input);
			$input = str_replace('$i','\'+$i+\'',$input);
			## empezamos a verificar si es la llave del array
			$soloId = !empty($campo['key'])?true:false;
			$ckecked = '';
			if($soloId){
				$ckecked = '<input type="checkbox" name="campos[]" id="Id\'+$i+\'" value="\'+$(\'#'.$this->getId($campo['campo'],true).'\').val()+\'" class="camposLista'.$modelHead.'">';									
				$thtml.= '$thtml= $thtml+\''. sprintf($this->tags['td'], $atrCelda ,$ckecked).'\';'.$n;
			}
			if(!empty($campo['hidden'])){
				$camposHidden.= $input;
			}elseif(!empty($campo['text'])){
				$soloInput = $input;
			}elseif(!empty($campo['checkbox'])){				
				$valorFila 	= '$(\'#'.$this->getId($campo['campo'],true).'\').attr(\'checked\')';
				$soloInput 	= '\'+'.$valorFila.'+\'';			
				$input		= str_replace('value','checked', $input);				
				//$input		= str_replace('<','', $input);				
				//printDie($inp);
				$soloInput = $input;	
			}elseif(!empty($campo['select'])){	
				$valorFila = '$(\'#'.$this->getId($campo['campo'],true).' option:selected\').text()';
				$soloInput = '\'+'.$valorFila.'+\'';			
				$camposHidden.= $input;	
			}else{							
				$soloInput = '\'+'.$valorFila.'+\'';				
				$camposHidden.= str_replace('text','hidden', $input);				
			}						
			# Acumulas en los TD
			if(!empty($soloInput)){						
				$thtml.= '$thtml= $thtml+\''.sprintf($this->tags['td'], $atrCelda ,$soloInput).'\';'.$n;
			}
		}
		$join = array_merge($this->defaultAttrhRef, array('href'=>'#','title'=>'Editar Registro','id'=>'edit\'+$i+\'','class'=>$edit));
		$botonEdit = sprintf($this->tags['aref'], $this->getProperty($join), $html->image($botom['edit']['texto']));
		//$thtml.= '$thtml= $thtml+\'<td>'.$botonEdit.$camposHidden.'</td>\';'.$n;
		$thtml.= '$thtml= $thtml+\''.sprintf($this->tags['td'], $editCelda ,$botonEdit.$camposHidden).'\';'.$n;
		# solo para el boton editar
		$editarFila.= '$("#'.$this->getId($insert['input']['name'],true).'").val($i);'.$n;
		
		$callbackAdd	= !empty($botom['add']['callback'])?$botom['add']['callback']:'';
		$callbackErase	= !empty($botom['erase']['callback'])?$botom['erase']['callback']:'';
		$callbackEdit	= !empty($botom['edit']['callback'])?$botom['edit']['callback']:'';
		
		$callOnAdd		= !empty($botom['add']['onAfter'])?$botom['add']['onAfter']:'';	
		$callOnErase	= !empty($botom['erase']['onAfter'])?$botom['erase']['onAfter']:'';
		$callOnEdit		= !empty($botom['edit']['onAfter'])?$botom['edit']['onAfter']:'';
		
		$body = '';
		$body.= '<script type="text/javascript">'.$n;
		$body.= '$(function(){'.$n;
		$body.= ' 				
				$(".select_all'.$modelHead.'").live("click",function(e){
					$check = $(this).attr("checked");
					if($check){							
						//$(".camposLista:checked").each(function(){
						$(".camposLista'.$modelHead.'").each(function(){	
							$(this).attr("checked",true);
						   	$(this).parents("tr:first").addClass("celdaTabla");
						});
					}else{
						$(".camposLista'.$modelHead.'").each(function(){
							$(this).attr("checked",false);
						   	$(this).parents("tr:first").removeClass("celdaTabla");
						});	
					}
				});
				// Si seleccionamos un checkbox de la tabla le quitamos el check de la class="select_all"
				$(".camposLista'.$modelHead.'").live("click",function(){
					$check = $(this).attr("checked");
					$(this).parents("tr:first").addClass("celdaTabla");						
					if(!$check){
						$(this).parents("tr:first").removeClass("celdaTabla");						
					}
					$(".select_all'.$modelHead.'").removeAttr("checked");	
                                        
				});		
				// redireccionamos con el botom
				reindex_inputs($(".'.$add.'"), true);		
				';
		// Editar Registros
		$eventoEdit = '';
		if(!empty($callOnEdit)){		
			if(is_array($callOnEdit)){				
				$eventoEdit = $callOnEdit['function'];
			}else{
				$eventoEdit = $callOnEdit.'($(\'#'.$afterFilaKey.'_\'+$i))';
			}
		}

		$body.= '
				$(".'.$edit.'").live("click", function(e){
                                        /* ARN */
                                        if($("img.buscar_proveedor_loader").length){
                                            alerta("Espere un momento porfavor, se esta realizado la consulta respectiva", "ADCSoft::Validacion", "critical");
                                            return false;
                                        }    

					e.preventDefault();
					$i = $(this).attr("id").substr(4);
					'.$callbackEdit.'
					// $("tr:#'.$afterFilaKey.'_"+$i+"").hide(); // SOLO PARA OCULTAR LA FILA
					$("tr[id*='.$afterFilaKey.'_]").removeClass("celdaTabla'.$modelHead.'"); 	
					$("tr:#'.$afterFilaKey.'_"+$i+"").addClass("celdaTabla'.$modelHead.'");					
					'.$editarFila.'
					
					'.$eventoEdit.'
				});	';		
		// Eliminar Registros
		$divChecked = '.camposLista'.$modelHead;
		if(!empty($this->onlyStyle['type']['div'])){
			if(!empty($this->onlyStyle['type']['div']['class'])){
				$divChecked = '.'.$this->onlyStyle['type']['div']['class'];
			}elseif(!empty($this->onlyStyle['type']['div']['id'])){
				$divChecked = '#'.$this->onlyStyle['type']['div']['div'];
			}
		}
						
		$body.= '
				$(".'.$delete.'").live("click",function(e){
						// acumulamos los campos para elminar
						'.$callbackErase.'
						$check = validarCheck'.$modelHead.'();
						if(!$check){													
							return false;
						}
						$anteriorItem= $("#'.$defaultBorrar.'").val();
						$totalItem	 = 0;
						$nuevoItem 	 = "";
						$coma		 = ",";
						$(".camposLista'.$modelHead.'").each(function(){
							$check = $(this).attr("checked");
							$fila  = $(this).attr("id").substring(2);
							$valor = $(this).attr("value");
							if($check){
								if($valor!=0){
									$nuevoItem+= $coma+$valor;
								}
								$("tr:#'.$afterFilaKey.'_"+$fila+"").remove();
							}
						});	
						if($nuevoItem!=""){	
							$("#'.$defaultBorrar.'").val($anteriorItem+$nuevoItem);				
							alerta("Eliminacion Correcta.","Mensaje",2500);
						}	
						//$("'.$divChecked.' input[type=checkbox]").attr("checked",false);
						//$(":checked").attr("checked",false);	
						contarRegistros'.$modelHead.'();						
						'.$callOnErase.'
						return false;
				});';		
		# botom agregar
		$eventoAdd = '';
		if(!empty($callOnAdd)){
			if(is_array($callOnAdd)){				
				$eventoAdd = $callOnAdd['function'];
			}else{
				$eventoAdd = $callOnAdd;//.'($(\'#'.$afterFilaKey.'_\'+$i))';
			}
		}
		
		$body.= '            
				$(".'.$add.'").click(function(e){ 
                                        /* FILTRO BY PABLO */
                                        if($("img.buscar_proveedor_loader").length){
                                            alerta("Espere un momento porfavor, se esta realizado la consulta respectiva", "ADCSoft::Validacion", "critical");
                                            return false;
                                        }    
                                        
					e.preventDefault();
					'.$callbackAdd.'
					$i = parseInt($("#'.$defaultTotal.'").val())+1;
					$tr = parseInt($("#'.$tr.'").val());
					if($tr>0){
						$i = $tr;
					}
					'.$onlyToChecked.'
					$thtml = "";
				  	$thtml = $thtml+\'<tr id="'.$afterFilaKey.'_\'+$i+\'">\';
					'.$thtml.'						
					$thtml = $thtml+\'</tr>\';						
					if($tr<=0){
						$($thtml).insertAfter("#'.$afterFila.'");	
						$("#'.$defaultTotal.'").val($i);
					}else{
						$("#'.$afterFilaKey.'_"+$tr).replaceWith($thtml);		
					}		
					$("#'.$afterFila.' :input").val(""); 
					$("#'.$this->getId($insert['input']['name'],true).'").val("-1");		
					
					'.$validacionChecked.'
										
					validarCeldasClick'.$modelHead.'();	
					contarRegistros'.$modelHead.'();	
					
					'.$eventoAdd.'				
					//reindex_inputs();                                        
					return false;				
				});'.$n.'';	
					
		$body.= '});';	
		$body.= '
				function validarCeldasClick'.$modelHead.'(){
					$("tr[id*='.$afterFilaKey.'_] td[class!=colCheck]").dblclick(function(){
						$(this).parent().addClass("celdaTabla");
						$(this).parent().find("a.'.$edit.'").click();						
						$(this).parent().siblings().removeClass("celdaTabla");						
					});    
				}
				
				function contarRegistros'.$modelHead.'(){
					$totalRegistros = 0;	
					$(".camposLista'.$modelHead.'").each(function(){
						$totalRegistros+=1;	
					});
					if($totalRegistros>12){
						$(".ultimoRegistro'.$modelHead.'").show().css({"font-weight":"bold"});	
					}else{
						$(".ultimoRegistro'.$modelHead.'").hide();
					}
					$(".mostrarTotalCelda'.$modelHead.'").text("Total registros : "+$totalRegistros+"").css({"font-weight":"bold"});
					return $totalRegistros;
				}	
				
				function validarCheck'.$modelHead.'(){
					$flag = true;
					$total= 0;
					$(".camposLista'.$modelHead.'").each(function(){
						$check = $(this).attr("checked");
						if($check){
							$total+=1;	
						}
					});
					if($total<=0){
						alerta("Seleccione al menos un registro.","Mensaje",2000);
						$flag = false;
					}
					return $flag;	 
				}			
				';		
		$body.= '</script>'.$n;
		return $body;
	}
	# construimos el jquery
    function builtList($arg=array()){
		$n 			= chr(13); // igual que <br>;
		$form 		= $this->Form;
		$html 		= $this->Html;		
		$textDate	= $this->TextDate;		
		$hidden 	='';
		$soloVista 	= false;
		if(!empty($arg['view'])){
			$soloVista = true;
		}
		// SOLO PARA CAMPOS DE BORRADO Y CONTADOR
		$defaultTotal	= 'Total.item';
		$defaultBorrar 	= 'Borrar.item';
		if(!empty($arg['count'])){
			$defaultTotal	= $arg['count']['total'];
			$defaultBorrar 	= $arg['count']['borrar'];
		}
		
		
		if(!$soloVista){
			$arg['botom']['edit'] 	= array_merge($this->botom['botom']['edit'] ,empty($arg['botom']['edit'])?array():$arg['botom']['edit']);	
			$arg['botom']['add'] 	= array_merge($this->botom['botom']['add'] ,empty($arg['botom']['add'])?array():$arg['botom']['add']);	
			$arg['botom']['erase'] 	= array_merge($this->botom['botom']['erase'],empty($arg['botom']['erase'])?array():$arg['botom']['erase']);	
		
			$botonAdd 	= $arg['botom']['add'];
			$add 		= !empty($botonAdd['img'])?$html->image($botonAdd['texto']):$botonAdd['texto'];
			$add 		= '<a'.$this->getProperty($botonAdd['atr']).'>'.$add.'</a>';
			$addCelda 	= !empty($botonAdd['celda'])?$this->getProperty($botonAdd['celda']):'';
			$botonEdit	= $arg['botom']['edit'];		
			$botonErase	= $arg['botom']['erase'];				
			$erase 		= !empty($botonErase['img'])?$html->image($botonErase['texto']):$botonErase['texto'];
			$erase 		= '<a'.$this->getProperty($botonErase['atr']).'>'.$erase.'</a>';
			$eraseCelda = !empty($botonErase['celda'])?$this->getProperty($botonErase['celda']):'';
		}
		# solo para los nombres de los campos
		$modelHead = 'Fila';
		$modelBody = 'Detalle';	
			
		$trInsert  = 'row0'; // PARA VER DESPUES DE QUE TR INGRESAR
		$trInsertKey= 'row';
		if(!empty($arg['insert']['after'])){
			$trInsert  = empty($arg['insert']['after']['atr']['id'])?$trInsert:$arg['insert']['after']['atr']['id']; // PARA VER DESPUES DE QUE TR INGRESAR
			$trInsertKey= empty($arg['insert']['after']['atr']['key'])?$trInsertKey:$arg['insert']['after']['atr']['key'];                   
		}
		$trFila    = $form->input($arg['insert']['input']['name'], $arg['insert']['input']['atr']); 		
		if(!empty($arg['model'])){
			$modelHead = $arg['model']['head']['name'];
			$modelBody = $arg['model']['body']['name'];
		}
		# Acumulamos el TD de los titulos
		$tdTitle= '';	
		$tdFila = '';
		if(!$soloVista){
			$tdTitle=  sprintf($this->tags['td'], '',$form->checkbox('select_id',array('class'=>'select_all'.$modelHead,'title'=>'seleccionar todo','name'=>'SelAll')));		
			$tdFila =  sprintf($this->tags['td'], '','-');
		}else{
			$tdTitle = sprintf($this->tags['th'], '','Item');	
		}	
		$cadena = '';
		foreach($arg['fieldsHead'] as $key=>$atr){
			$atrTable = ''; // solo para atributos de tabla
			if(!empty($atr['celda'])){						
				$atrTable = $this->getProperty($atr['celda']);			
			}
			$atributos = array_merge($this->defaultAttr,!empty($atr['atr'])?$atr['atr']:array());
			if(!empty($atr['title'])){	
				if($soloVista){
					$tdTitle.= sprintf($this->tags['th'], $atrTable , $atr['title']);
				}else{
					$tdTitle.= sprintf($this->tags['td'], $atrTable , '<strong>'.$atr['title'].'</strong>');	
				}
				if(!empty($atr['type']) && (!$soloVista)){
					switch($atr['type']){						
						case 'input':
							$tdFila.= sprintf($this->tags['td'], $atrTable , $form->input($modelHead.'.'.$key , $atributos));	
						break;						
						case 'hidden':
							$hidden.= $form->hidden($modelHead.'.'.$key, $atributos);
						break;	
						case 'select':
							if(!$atributos['size']){
								unset($atributos['size']);
							}
							$tdFila.= sprintf($this->tags['td'], $atrTable , $form->input($modelHead.'.'.$key , $atributos));
						break;
						case 'checkbox':
							if(!$atributos['size']){
								unset($atributos['size']);
							}
							$tdFila.= sprintf($this->tags['td'], $atrTable , $form->input($modelHead.'.'.$key , $atributos));
						break;						
						case 'date':							
							$tdFila.= sprintf($this->tags['td'], $atrTable , $textDate->input($modelHead.'.'.$key , $atributos));
						break;						
					}
				}
						
			}else{									
				if(!empty($atr['type'])){	
					switch($atr['type']){						
						case 'input':
							$tdFila.= sprintf($this->tags['td'],  $atrTable , $form->input($modelHead.'.'.$key, $atributos));							
						break;						
						case 'hidden':
							$hidden.= $form->hidden($modelHead.'.'.$key, $atributos);
						break;						
					}
				}			
			}
			
		}	
		if(!$soloVista){
			$tdTitle.= sprintf($this->tags['td'], $eraseCelda , $erase).$n;		
			$tdFila.= sprintf($this->tags['td'], $addCelda , $add. $hidden. $trFila);	// Aqui juntamos todos los campos tipo hidden
		}
		# SOLO PARA DATA EN CASO DE EDICION
		$i = 1;
		$hiddenData = '';
		$onlyData = '';		
		if(!empty($arg['data'])){
			$this->i = 0;
			foreach($arg['data'] as $data){
				$class = '';
				if ($this->i++ % 2 == 0) {
                    $class = 'class="altrow"';
                }
				$onlyData.= '<tr id="'.$trInsertKey.'_'.$i.'" '.$class.'>';				
				# comprobamos que campos solo queremos mostrar		
				foreach($arg['fieldsBody'] as $key=>$campo){
					//echo $key.'<br />';
					$nameInput = $modelBody.'.'.$i.'.'.$this->getId($key); // nombre del inptu					
					$value = $this->getValue($data, $key, false);	
					if(!empty($campo['fields'])){
						$func = new ReflectionFunction('sprintf');
						$var = array();
						array_push($var,$campo['fields'][1]);
						foreach($campo['fields'][0] as $field=>$values){
							array_push($var,$this->getValue($data,$values,false));
						}
						$value = $func->invokeArgs($var);													
					}
					
					$atrTable = ''; // solo para atributos de tabla TD
					if(!empty($campo['celda'])){						
						$atrTable = $this->getProperty($campo['celda']);
					}
					# Atributos para la tabla en caso de que si tenga alig					
					if(!empty($campo['float'])){
						$float = $campo['float'];
						$value = empty($value)?0:$value;
						$value = number_format($value, $float,'.','');	
					}
					if(!empty($campo['date'])){	
						if(!empty($value)){
							$fecha = explode('-',$value);
							$value = $fecha[2].'/'.$fecha[1].'/'.$fecha[0];
						}
					}
					
					$atributo = array_merge($this->defaultAttr, array('value'=>$value)); // para los input
					if(!empty($campo['atr'])){
						$atributo = array_merge($atributo,!empty($campo['atr'])?$campo['atr']:array());	
					}
					// SOLO PARA EL CASO DE LOS VALUES
					$texto = array('value');
					if(!empty($campo['value'])){
						$texto['value']	= $this->getValue($data, $campo['value'], false);						
						//$texto['value']	= $this->getValue($data, $key, false);												
						unset($texto[0]);
						$atributo 	= array_merge($atributo, $texto);
						$value = $texto['value'];										
					}	
					if(!empty($campo['checkbox'])){	
						$atributo['checked'] = empty($atributo['value'])? FALSE : TRUE;
                                                unset($atributo['value']);
						$input = $form->checkbox($nameInput, $atributo);
                                                if(!$atributo['checked']){
                                                   $input = str_replace('checked','tag',$input);
                                                }
												
					}elseif(!empty($campo['selected'])){	
						# ESTE CASO ES SOLO es cuando hay un campo select, y deseamos obtener el otro valor a parte del value enviamo
						$atributo['value'] =  $this->getValue($data, $campo['selected'], false);
						$input = $form->text($nameInput, $atributo);
					}else{
						$input = $form->text($nameInput, $atributo);	
					}					
					## empezamos a verificar si es la llave del array 
					$soloId = !empty($campo['key'])?true:false;
					if($soloId){
						if(!$soloVista){
							$chekbox = '<input type="checkbox" value="'.$value.'" id="Id'.$i.'" class="camposLista'.$modelHead.'" name="data['.$i.'][id]">';
							$onlyData.= sprintf($this->tags['td'], 'class="colCheck" ',$chekbox);	
						}else{
							$onlyData.= sprintf($this->tags['td'], 'align="center" width="15"',$i);		
						}				
					}
					
					if(!empty($campo['hidden'])){						
						$hiddenData.= $input;
					}elseif(!empty($campo['text'])){						
						$onlyData.= sprintf($this->tags['td'], $atrTable , $input);						
					}elseif(!empty($campo['checkbox'])){
							$onlyData.= sprintf($this->tags['td'], $atrTable , $input);													
					}elseif(!empty($campo['select'])){	
						$texto = $value;						
						if(!empty($campo['value'])){							
							$texto = $this->getValue($data, $campo['value'], false);	
							$form->text($nameInput, $atributo);
							$onlyData.= sprintf($this->tags['td'], $atrTable , $texto);	
						}else{
							$onlyData.= sprintf($this->tags['td'], $atrTable , $texto);		
						}						
						$hiddenData.= $input;
					}else{
						$onlyData.= sprintf($this->tags['td'], $atrTable , $value);
						$hiddenData.= str_replace('text','hidden',$input);
					}
					
				}
				if(!$soloVista){
					$atributoEdit	= array_merge($botonEdit['atr'],array('id'=>'edit'.$i));
					$edit 			= !empty($botonEdit['img'])?$html->image($botonEdit['texto']):$botonEdit['texto'];
					$edit 			= '<a'.$this->getProperty($atributoEdit).'>'.$edit.'</a>';
					$editCelda 		= !empty($botonEdit['celda'])?$this->getProperty($botonEdit['celda']):'';
					$onlyData.=  sprintf($this->tags['td'], $editCelda, $edit . $hiddenData);
				}
				$onlyData.= '</tr>';
				$hiddenData ='';
				$i++;
			}			
		}
		$body ='';		
		# HACEMOS PARA LOS ESTILOS CSS
		$body.= $this->Css(empty($arg['style'])?array():$arg['style']);	
		
		if(!$soloVista){
			$body.= $this->jquery($arg['insert'], $arg['botom'], $arg['model'], $arg['fieldsHead'], $arg['fieldsBody'], !empty($arg['count'])?$arg['count']:'');
		}
		
		$body.= '<div '.$this->getProperty($this->onlyStyle['type']['div']).'>';	
		$soloTabla = empty($arg['table']['atr'])?$this->onlyStyle['type']['table'] : $arg['table']['atr'];
		$body.= '<table'.$this->getProperty( $soloTabla ).'>';				
		$body.= '<thead>';
		$body.= sprintf($this->tags['tr'], '', $tdTitle); # PARA LOS TITULOS	
		$body.= '</thead>';
		# miramos si hay atributos para el insert de cada tabla
		$body.= '<tbody>';		
		$body.= sprintf($this->tags['tr'], $this->getProperty($arg['insert']['after']['atr']), $tdFila); # PARA LOS CAMPOS			
		$body.=	$onlyData;
		$body.= '</tbody>';
		if(count($arg['data'])>12 && !empty($arg['dobleHead']) && (!$soloVista)){
			$body.= sprintf($this->tags['tr'], 'class="ultimoRegistro'.$modelHead.'"', $tdTitle); # PARA LOS TITULOS
		}
		$body.='</table>';	
		$totalRegistros = empty($arg['data'])?0:count($arg['data']);
		$body.='<div class="mostrarTotalCelda'.$modelHead.'" style="font-weight:bold;">Total registros : '.$totalRegistros.'</div>';	
		# solo para poder ver si hay data
		$pieItem = array_merge($this->defaultAttr,array('value'=>$i));
		
		$body.= $form->hidden( $defaultTotal , $pieItem);	
		$body.= $form->hidden( $defaultBorrar , array('value'=>0));			
					
		$body.= '</div>';	
		if(!$soloVista){			
			$body.= '<script type="text/javascript">';
			$body.= '$(function(){ ';
			$body.= '$(".ultimoRegistro'.$modelHead.'").hide();';
			if(!empty($arg['data'])){
				if(count($arg['data'])>12 && !empty($arg['dobleHead']) && (!$soloVista)){
					$body.= '	$(".ultimoRegistro'.$modelHead.'").show().css({"font-weight":"bold"}); ';
				}
			}
			$body.= '	validarCeldasClick'.$modelHead.'(); ';			
			$body.= '});';
			$body.= '</script>';
		}
		return $body;
	}
    	
    function getFunction($name){
            $this->userFunction = $name;
    }

    function restaFechas($dFecIni, $dFecFin){
        $dFecIni = str_replace('-','',$dFecIni);
        $dFecIni = str_replace('/','',$dFecIni);
        $dFecFin = str_replace('-','',$dFecFin);
        $dFecFin = str_replace('/','',$dFecFin);

        ereg( '([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})', $dFecIni, $aFecIni);
        ereg( '([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})', $dFecFin, $aFecFin);

        $date1 = mktime(0,0,0,$aFecIni[2], $aFecIni[1], $aFecIni[3]);
        $date2 = mktime(0,0,0,$aFecFin[2], $aFecFin[1], $aFecFin[3]);

        return round(($date2 - $date1) / (60 * 60 * 24));
    }

    function sumaFechas($givendate,$day=0,$mth=0,$yr=0) {
        $cd = strtotime($givendate);
        $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
                date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
                date('d',$cd)+$day, date('Y',$cd)+$yr));
        return $newdate;
    }

    function is_date($fecha){
        //Comprueba si la cadena introducida es de la forma D/m/Y (15/04/1920)
        if (ereg("([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})", $fecha, $bloques)){
            return checkdate($bloques[2], $bloques[3], $bloques[1]);
        } else if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $fecha, $bloques)){
            return checkdate($bloques[2], $bloques[3], $bloques[1]);
        } else return false;
        return true;
    }	
	
}
?>